package com.globaldom.web;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.globaldom.model.Deployment;
import com.globaldom.model.PersonLocation;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/getdeployment")
public class DeploymentGetController {

	public DeploymentGetController() {
	}
	//
	// initializing method
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model, HttpSession session) {
		return "territory";
	}

	@RequestMapping(value = "/get", method = RequestMethod.POST)
	public String getMyDeployment(@RequestParam String locID, Model model, HttpSession session, HttpServletRequest request) {
		Map<Integer, Long> map = null;
		Map<Integer, Long> deployedRes = null;
	
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			return "loggedout";
			}
		// FIXME extract this up the calling chain so it's called once per
		// session start and
		// stored in javascript array. Less secure but faster
		Integer distance = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {

			map = MemCacheManager.getDeployment(personID, locID);
			if (null == map) {
				map = new HashMap<Integer, Long>();
				Query query = pm.newQuery(PersonLocation.class, "id==locid && person==pid");
				query.declareParameters("long locid,String pid");
				PersonLocation location = (PersonLocation) ((List<PersonLocation>) query.execute(locID, personID)).get(0);
				distance = location.getDistance();

				query = pm.newQuery(Deployment.class, "personLocation==locid");
				query.declareParameters("long locid");
				List<Deployment> deployment = (List<Deployment>) query.execute(locID);

				for (Iterator<Deployment> iterator = deployment.iterator(); iterator.hasNext();) {
					Deployment engDep = (Deployment) iterator.next();
					map.put(engDep.getResourceType(), engDep.getAvailResources());
				}

				MemCacheManager.putDeployment(personID, locID, map);
				MemCacheManager.putDistance(personID, locID, distance);
			}
			if (distance == null) {
				distance = MemCacheManager.getDistance(personID, locID);
				if(null==distance)
				{
					
				}
			}

			deployedRes = MemCacheManager.getFreeResources(personID);
			if (null == deployedRes) {

				Query query = pm.newQuery( "Select ResourceType,sum(AvailResources) from " + Deployment.class.getName() + " where person==pid group by ResourceType");
				query.declareParameters("String pid");
				List<Deployment> deployment = (List<Deployment>) query.execute(personID);

				for (Iterator<Deployment> iterator = deployment.iterator(); iterator.hasNext();) {
					Deployment engDep = (Deployment) iterator.next();
					deployedRes.put(engDep.getResourceType(), engDep.getAvailResources());
				}
				MemCacheManager.putFreeResources(personID, deployedRes);
			}

			model.addAttribute("currentDeployed", map);
			model.addAttribute("freeResources", deployedRes);
			model.addAttribute("dep", locID);
			model.addAttribute("distance", distance);
			model.addAttribute(Constants.CODE, "+OK");

		} catch (Exception edea) {
			// FIXME. The said territory has been looted but the user is not
			// aware!
			model.addAttribute(Constants.CODE, "-ER");
			model.addAttribute(Constants.DATA, "EDE" + edea.getMessage());
			MemCacheManager.removeLocations(personID);
			MemCacheManager.removeDeployments(personID, locID);
			MemCacheManager.removeFreeResources(personID);
		} finally {
			pm.close();
		}

		return "deployment";
	}

}
